package com.yanyilu.qiubite.service;

import com.alibaba.fastjson.JSON;
import com.yanyilu.qiubite.entity.*;
import com.yanyilu.qiubite.jpa.PartJpa;
import com.yanyilu.qiubite.jpa.StoryIndexJpa;
import com.yanyilu.qiubite.jpa.StorylineJpa;
import com.yanyilu.qiubite.jpa.UserJpa;
import com.yanyilu.qiubite.util.Base64Util;
import com.yanyilu.qiubite.util.R;
import com.yanyilu.qiubite.util.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedList;
import java.util.List;
import java.util.Optional;

@Service
public class StoryIndexService {
    @Autowired
    StoryIndexJpa storyIndexJpa;

    @Autowired
    StorylineJpa storylineJpa;

    @Autowired
    PartJpa partJpa;

    @Autowired
    UserJpa userJpa;


    //保存游戏进度
    public R createIndex(Integer partId, Integer userid) {
        StoryIndex storyIndex = null;
        storyIndex = storyIndexJpa.findbyUserIdAndPartId(userid,partId);
        if(null != storyIndex){
            return R.ok();
        }
        Optional<Part> optional = partJpa.findById(partId);
        if(optional.isPresent()){
            //获取当前十位时间戳
            int time = (int)(System.currentTimeMillis()/1000);
            Part part = optional.get();
            storyIndex = new StoryIndex();
            storyIndex.setCompletedNum(0);
            storyIndex.setRemainingTimes(part.getHasTimes());
            storyIndex.setEndTime(time+(part.getTotalTime()*60));
            storyIndex.setUserId(userid);
            storyIndex.setPartId(partId);

            //将故事线取出并转为字符串存入表中
            List<Storyline> list = storylineJpa.findListByPartId(partId);
            List<StoryCard> lines = new LinkedList<>();
            StoryCard storyCard;
            for (Storyline storyline : list) {
                storyCard = new StoryCard();
                storyCard.setLineId(storyline.getLineId());
                storyCard.setLineName(storyline.getLineName());
                storyCard.setLinePic(storyline.getLinePic());
                storyCard.setPartName(part.getPartName());
                storyCard.setLineCard(storyline.getLineCard());
                storyCard.setLineState(0);
                lines.add(storyCard);
            }
            String json = JSON.toJSONString(lines);
            storyIndex.setStoryLine(json);
            synchronized (storyIndexJpa) {
                storyIndexJpa.save(storyIndex);
            }
            return R.ok();
        }else{
            return R.error(ResultCode.DATA_IS_WRONG);
        }
    }

    //获取游戏进度
    public R getStoryIndex(Integer userid,Integer partId) {
        Optional<User> optional = userJpa.findById(userid);
        if(optional.isPresent()){
            StoryIndex storyIndex = storyIndexJpa.findbyUserIdAndPartId(userid,partId);
            if(null != storyIndex){
                return R.ok().put("storyIndex",storyIndex);
            }else{
                return R.error(ResultCode.SYSTEM_INNER_ERROR);
            }
        }else{
            return R.error(ResultCode.USER_NOT_EXIST);
        }

    }

    //验证答案
    @Transactional
    public R checkAnswer(Integer userid, Integer lineId, String lineAnswer) {
        //解码
        String answer = "";
        try {
            answer = Base64Util.decode(lineAnswer);
        } catch (Exception e) {
            return R.exp("无效码");
        }
        Optional<Storyline> optional = storylineJpa.findById(lineId);
        Storyline storyline;
        if(optional.isPresent()){
            storyline = optional.get();
        }else {
            return R.error("系统繁忙");
        }
        //获取
        StoryIndex storyIndex = storyIndexJpa.findbyUserIdAndPartId(userid,storyline.getPartId());
        String storyLine = storyIndex.getStoryLine();
        //解析为故事卡
        List<StoryCard> storyCards = JSON.parseArray(storyLine, StoryCard.class);
        //正确
        if(answer.equals(storyline.getLineAnswer())){
            for (StoryCard storyCard : storyCards) {
                if(lineId.equals(storyCard.getLineId())){
                    if(storyCard.getLineState()!=1){
                        storyCard.setLineState(1);
                        storyIndex.setCompletedNum(storyIndex.getCompletedNum()+1);

                        Optional<User> op = userJpa.findById(userid);
                        User user;
                        if(op.isPresent()){
                            user = op.get();
                            user.setTaskCount(user.getTaskCount()+1);
                            userJpa.save(user);
                        }else {
                            return R.error(ResultCode.USER_NOT_EXIST);
                        }
                    }
                }
            }
            String jsonString1 = JSON.toJSONString(storyCards);
            storyIndex.setStoryLine(jsonString1);
            storyIndexJpa.save(storyIndex);

            return R.ok("解密成功");
        }else{
            //错误
            storyIndex.setRemainingTimes(storyIndex.getRemainingTimes()-1);
            storyIndexJpa.save(storyIndex);
            return R.error("解密失败");
        }
    }

    @Transactional
    public R restart(Integer userid) {
        storyIndexJpa.deleteByUserId(userid);
        Optional<User> op = userJpa.findById(userid);
        if(op.isPresent()){
            User user = op.get();
            user.setTaskCount(0);
            userJpa.save(user);
        }else {
            return R.error(ResultCode.USER_NOT_EXIST);
        }
        return R.ok();
    }
}
